package com.lingjtx.gencode;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CommonUtils {

    /**
     * 将数据库字段类型映射到 Java 类型
     */
    public static String mapToJavaType(String columnType) {
        return switch (columnType.toUpperCase()) {
            case "INT", "INT UNSIGNED" -> "Integer";
            case "BIGINT", "BIGINT UNSIGNED" -> "Long";
            case "TINYINT UNSIGNED", "TINYINT" -> "Byte";
            case "SMALLINT", "SMALLINT UNSIGNED" -> "Short";
            case "FLOAT" -> "Float";
            case "DOUBLE" -> "Double";
            case "DECIMAL UNSIGNED", "DECIMAL" -> "java.math.BigDecimal";
            case "BOOLEAN" -> "Boolean";
            case "DATE", "DATETIME", "TIMESTAMP" -> "Date";
            case "BLOB" -> "byte[]";
            default -> "String";
        };
    }

    /**
     * 将表名转换为驼峰命名
     */
    public static String toCamelCase(String tableName, boolean isClass) {
        StringBuilder result = new StringBuilder();
        String[] parts = tableName.split("_");
        for (String part : parts) {
            result.append(part.substring(0, 1).toUpperCase()).append(part.substring(1));
        }
        return isClass ? result.toString() : result.substring(0, 1).toLowerCase() + result.substring(1);
    }

    /**
     * 生成文件
     */
    public static void generateFile(VelocityEngine velocityEngine, VelocityContext context, String templateName, String outputPath) throws IOException {
        // 转换为 Path 对象
        Path path = Paths.get(outputPath);
        // 获取父目录
        Path parentDir = path.getParent();
        // 如果父目录不存在，则创建
        if (!Files.exists(parentDir)) {
            try {
                Files.createDirectories(parentDir);
                System.out.println("目录创建成功: " + parentDir.toAbsolutePath());
            } catch (IOException e) {
                System.err.println("目录创建失败: " + e.getMessage());
                return;
            }
        }

        if (Files.exists(path)) {
            return;
        }

        Template template = velocityEngine.getTemplate(templateName);
        StringWriter writer = new StringWriter();
        template.merge(context, writer);

        try (FileWriter fileWriter = new FileWriter(outputPath)) {
            fileWriter.write(writer.toString());
        }
    }
}
